<template>
  <div class="box">
    <el-card class="card-css">
      <div class="zhpj">
        <span class="zhpj-span">工单配置</span>
      </div>
      <div class="table-css">
        <div>
          <span>不经确认，直接发出</span>
          <el-switch v-model="value1" class="switch-css" />
        </div>
        <div class="biaotou-css">
          <div class="select02">
            <el-select placeholder="能效">
              <el-option label="Zone one" value="shanghai" />
              <el-option label="Zone two" value="beijing" />
            </el-select>
          </div>

          <div class="block">
            <el-date-picker type="daterange" :disabled-date="disabledDate" range-separator="至" start-placeholder="开始时间"
              end-placeholder="结束时间" />
          </div>

          <div class="btn-01">
            <el-button type="primary" @click="exportExcel">下 载</el-button>
          </div>
          <div class="btn-02">
            <!-- <el-button type="primary">打 印</el-button> -->
          </div>
        </div>
      </div>

      <div class="table">
        <el-table id="table" :data="tableData" stripe border height="600" style="width: 100%" :header-cell-style="{
          'text-align': 'center',
          background: '#B4C7E7',
          color: '#333333',
        }" :cell-style="{
  'text-align': 'center',
  background: '#f5f8fb',
}">
          <el-table-column prop="date" width="90px" label="确认发出">
            <template #default="scope">
              <span>
                <el-button @click="quren(scope.$index, scope.row)" :icon="ArrowRight" circle
                  style="color: #f79646; background: #eaf2fa; border: #eaf2fa" />
              </span>
            </template>
          </el-table-column>
          <el-table-column width="100px" label="触发">
            <template #default="scope">
              <!-- <span>{{ dayjs(scope.row.triggeringTime).format('YYYY-MM-DD') }}</span> -->
              <p>
                {{
                  dayjs(scope.row.triggeringTime || "1").format(
                    "YYYY-MM-DD HH:mm:ss"
                  )
                }}
              </p>
            </template>
          </el-table-column>
          <el-table-column label="预计完成" width="100px">
            <template #default="scope">
              <p>
                {{
                  dayjs(scope.row.expectedCompletionTime || "1").format(
                    "YYYY-MM-DD HH:mm:ss"
                  )
                }}
              </p>
            </template>
          </el-table-column>
          <el-table-column prop="problemDescription" label="问题描述" width="120px" />
          <el-table-column prop="possibleCause" width="110px" label="可能原因" />
          <el-table-column prop="friendlyReminder" width="100px" label="友情提示" />
          <el-table-column prop="urgencyType" label="紧急类别" :filters="[
            { text: '1', value: 0 },
            { text: '2', value: 1 },
            { text: '3', value: 2 },
            { text: '4', value: 4 },
            { text: '5', value: 5 },
          ]" :filter-method="filterTagUrgency" width="90px" align="center" />
          <el-table-column prop="workOrderType" label="工单类别" :filters="[
            { text: '优化操作', value: 0 },
            { text: '设备故障', value: 1 },
            { text: '预测性维护', value: 2 },
          ]" :filter-method="filterTagWork_order" width="90px" align="center">
            <template #default="scope">
              <span v-if="scope.row.workOrderType == '0'">优化操作</span>
              <span v-if="scope.row.workOrderType == '1'">设备故障</span>
              <span v-if="scope.row.workOrderType == '2'">预测性维护</span>
            </template>
          </el-table-column>
          <el-table-column prop="influenceType" label="影响范围" :filters="[
            { text: '能效', value: 0 },
            { text: '舒适', value: 1 },
            { text: '安全', value: 2 },
            { text: '所有', value: 3 },
          ]" :filter-method="filterTagInfluenceType" width="90px" align="center">
            <template #default="scope">
              <span v-if="scope.row.influenceType == '0'">能效</span>
              <span v-if="scope.row.influenceType == '1'">舒适</span>
              <span v-if="scope.row.influenceType == '2'">安全</span>
              <span v-if="scope.row.influenceType == '3'">所有</span>
            </template>
          </el-table-column>
          <el-table-column prop="riskType" label="风险" :filters="[
            { text: '高', value: 0 },
            { text: '中', value: 1 },
            { text: '低', value: 2 },
          ]" :filter-method="filterTagRiskType" width="90px" align="center">
            <template #default="scope">
              <span v-if="scope.row.riskType == '0'">高</span>
              <span v-if="scope.row.riskType == '1'">中</span>
              <span v-if="scope.row.riskType == '2'">低</span>
            </template>
          </el-table-column>
          <el-table-column prop="involveEquipmentSystem" label="涉及设备/系统" :filters="[
            { text: '制冷机', value: 0 },
            { text: '冷冻泵', value: 1 },
            { text: '冷却泵', value: 2 },
            { text: '冷却塔', value: 3 },
            { text: 'BA系统', value: 4 },
            { text: '热水崩', value: 5 },
          ]" :filter-method="filterTagInvolveEquipmentSystem" width="150px" align="center" />
          <el-table-column prop="operationalOrder" label="操作指令" width="292px" />
          <el-table-column prop="executiveName" label="执行人员姓名" align="center"></el-table-column>

          <el-table-column prop="executiveCondition" label="发出情况" :filters="[
            { text: '已发出', value: 0 },
            { text: '未发出', value: 1 },
            // { text: '安全', value: 2 },
            // { text: '所有', value: 3 },
          ]" :filter-method="filterTagExecutiveCondition" align="center">
            <template #default="scope">
              <div v-show="scope.row.executiveCondition == '0'">已发出</div>
              <div v-show="scope.row.executiveCondition == '1'">未发出</div>
            </template></el-table-column>
          <el-table-column prop="address" width="150px" label="详情查看">
            <template #default="scope">
              <el-button @click="handleid(scope.row)((dialogVisible = true))" round size="small">详情查看</el-button>
            </template>
            <!-- <span >详情查看</span> -->
          </el-table-column>
        </el-table>
      </div>
      <div class="pagination">
        <el-pagination v-model:currentPage="currentPage" layout="prev, pager, next, jumper" :total="total"
          @current-change="handleCurrentChange" />
      </div>
    </el-card>

    <!-- 弹出详情查看对话框 -->
    <el-dialog v-model="dialogVisible" width="50%">
      <template #title>
        <div class="my-header">
          <div>
            <span>工单编号</span> <span>{{ form.data.workOrderNo }}</span>
          </div>
        </div>
      </template>
      <el-divider class="line" />

      <el-form>
        <div class="detail">
          <div class="tm">
            <div class="timer">
              <p>剩余时间</p>
              <p class="time">
                {{
                  dayjs(form.data.remainingTime || "1").format(
                    "YYYY-MM-DD HH:mm:ss"
                  )
                }}
              </p>
            </div>

            <div class="timer">
              <p>触发时间</p>
              <p class="time">
                {{
                  dayjs(form.data.triggeringTime || "1").format(
                    "YYYY-MM-DD HH:mm:ss"
                  )
                }}
              </p>
            </div>

            <div class="timer">
              <p>预期完成时间</p>
              <p class="time">
                {{
                  dayjs(form.data.expectedCompletionTime || "1").format(
                    "YYYY-MM-DD hh:mm:ss"
                  )
                }}
              </p>
            </div>
          </div>

          <div class="question">
            <div class="center">
              <el-form-item label="问题描述">
                <el-input v-model="form.data.problemDescription" input-style="height:60px" type="textarea" />
              </el-form-item>
            </div>

            <div class="center">
              <el-form-item label="可能原因">
                <el-input v-model="form.data.possibleCause" input-style="height:60px" type="textarea" />
              </el-form-item>
            </div>

            <div class="center">
              <el-form-item label="操作指令">
                <el-input v-model="form.data.operationalOrder" input-style="height:120px;" type="textarea" />
              </el-form-item>
            </div>

            <div class="center">
              <el-form-item label="友情提示">
                <el-input v-model="form.data.friendlyReminder" input-style="height:60px" type="textarea" />
              </el-form-item>
            </div>
          </div>

          <div class="right">
            <div class="detail">
              <el-form-item label="已达级别">
                <el-input v-model="form.data.executiveName" />
              </el-form-item>
            </div>

            <div class="success">
              <el-form-item label="无法执行">
                <el-input v-model="form.data.cannotExecute" placeholder="无法执行理由陈述" input-style="height:92px;width:250px"
                  type="textarea" />
              </el-form-item>
              <el-button size="small" class="commit" @click="commit">确认提交</el-button>
            </div>

            <div class="success">
              <el-form-item label="成功执行">
                <el-input v-model="form.data.successfulExecution" placeholder="执行过程陈述"
                  input-style="height:92px;width:250px" type="textarea" />
              </el-form-item>
              <el-button size="small" class="commit" @click="commit">确认提交</el-button>
            </div>
            <div class="success">
              <div>
                <el-button size="small" class="commit" @click="dialogVisible = false"
                  style="margin-left: 150px">取消</el-button>
              </div>
              <div>
                <el-button size="small" class="commit" @click="putConfig(form)">确认</el-button>
              </div>
            </div>
          </div>
        </div>
      </el-form>
    </el-dialog>
  </div>
</template>

<script setup>
import { onMounted, ref, reactive, watch } from "vue";
import { ArrowRight } from "@element-plus/icons-vue";
import {
  getConfiguration,
  updateConfiguration,
  getQueryAdd,
  delWorkerOrder,
} from "@/api/model/echarts";
import pubsub from "pubsub-js";
// import { WorkOrderId } from "@/api/model/end";
import FileSaver from "file-saver";
import * as XLSX from "xlsx/dist/xlsx.mini.min.js";
import dayjs from "dayjs";
const value1 = ref(false);
var dialogVisible = ref(false);
let form = reactive({
  data: {},
});
const disabledDate = (time) => {
  return time.getTime() > Date.now();
};
const filterTagInfluenceType = (value, row) => {
  return row.influenceType == value;
};

const filterTagRiskType = (value, row) => {
  return row.riskType == value;
};

const filterTagExecutiveCondition = (value, row) => {
  return row.executiveCondition == value;
};
const filterTagInvolveEquipmentSystem = (value, row) => {
  return row.involveEquipmentSystem == row.involveEquipmentSystem;
};
const filterTagUrgency = (value, row) => {
  return row.urgencyType == value;
};
const filterTagWork_order = (value, row) => {
  return row.workOrderType == value;
};

const currentPage = ref(1);
const total = ref(2);
const len = ref(0);
const tableData = ref([]);

//初始化页面获取数据
const getdata = async () => {
  let { data: res } = await getConfiguration({ page: currentPage.value });
  console.log(res, "wwwwwwwwwwwwwwwwwwwwww");
  tableData.value = res.data.list.slice(0, 2);
  tableData.value.sort((a, b) => b.createTime - a.createTime);
  len.value = res.data.total;
  // total.value = res.data.total;
  delitems();
};
//监听是否直接发出状态
watch(value1, (newVal) => {
  // 不确认发出按钮状态本地保存
  // window.sessionStorage.setItem("gdIsChecked", newVal);
  window.localStorage.setItem("gdIsChecked", newVal);
  if (newVal) {
    tableData.value.forEach((item) => {
      quren(-1, item);
    });
  } else {
    return false;
  }
});
//判断操作问题
const delitems = async () => {
  if (value1.value) {
    return false;
  }
  let datas = [];
  let res = await getConfiguration({
    page: currentPage.value,
    workOrderType: "0",
  });
  datas = res.data.data.list;
  console.log(res, 470);

  if (datas) {
    if (datas.length > 2) {
      for (let i = 2; i < 10; i++) {
        await delWorkerOrder({ ids: datas[i].id });
      }
    }
  }
};
const handleCurrentChange = (val) => {
  currentPage.value = val;
  getdata();
};
// 修改功能
const putConfig = (e) => {
  console.log(e.data);
  dialogVisible.value = !dialogVisible.value;
};
//详情查看功能
const handleid = async (e) => {
  form.data = {};
  // let res = await WorkOrderId(e.id);
  form.data = e;
  // console.log(res, "WorkOrderIdWorkOrderId");
};
//确认提交按钮
async function commit() {
  console.log(form.data);
  await updateConfiguration(form.data);
  getdata();
  dialogVisible.value = false;
}
//点击左侧箭头，提交到工单列表
const quren = async (id, e) => {
  console.log(id);
  await delWorkerOrder({ ids: e.id });
  e.messageType = 0;
  e.id = "";
  e.executiveName = eval(window.localStorage.getItem("USER_INFO"));
  for (const key in e) {
    if (e[key] == null) {
      e[key] = "1";
    }
  }
  await getQueryAdd(e);
  pubsub.publish("updateList");
  getdata();
};
function exportExcel() {
  //需给表格定义一个id或者类名
  console.log("1111111111", XLSX);
  let wb = XLSX.utils.table_to_book(document.querySelector("#table"));
  console.log("222");
  let wbout = XLSX.write(wb, {
    bookType: "xlsx",
    bookSST: true,
    type: "array",
  });
  try {
    FileSaver.saveAs(
      new Blob([wbout], { type: "application/octet-stream" }),
      "111.xlsx"
    ); //***是自己导出文件时的命名，随意
  } catch (e) {
    if (typeof console !== "undefined") console.log(e, wbout);
  }
  return wbout;
}

//监听数组数据,实现自动添加数据
const putMsgAuto = () => {
  if (tableData.value.length < 1) {
    return false;
  }
  if (!value1.value) {
    return false;
  }
  tableData.value.forEach((msg) => {
    quren(-1, msg);
  });
};
// watch(len, (newValue, oldValue) => {
//   setTimeout(() => {
//     console.log("新值是" + newValue, "旧址是" + oldValue);
//   }, 5000);

//   if ((newValue - oldValue) == 1 && value1.value == true) {
//     let data = tableData[newValue];
//     updateWorkerOrder(data);
//   }
// });

onMounted(() => {
  getdata();
  setInterval(() => {
    delitems();
    putMsgAuto();
  }, 60000);
  const check = JSON.parse(window.localStorage.getItem("gdIsChecked"));
  if (check) {
    value1.value = check;
    tableData.value.forEach((item) => {
      quren(-1, item);
    });
  }


});
</script>

<style lang="less" scoped>
.detail {
  width: 100%;
  display: flex;

  .tm {
    width: 50%;

    .timer {
      width: 100%;
      margin-top: 20px;

      p:first-child {
        font-size: 12px;
        margin: 10px 0;
      }

      .time {
        color: #4d62a5;
        font-size: 12px;
      }
    }
  }

  .question {
    height: 100%;

    .center {
      width: 100%;
      height: 10%;
      margin: 1% 0;
    }
  }

  .right {
    height: 100%;

    .success {
      height: 100px;
      position: relative;

      :deep(.el-button) {
        height: 30px;
        position: absolute;
        left: -3%;
        top: 30%;
        color: #fff;
        width: 60px;
        background: #8faadc;
      }
    }
  }

  .question,
  .tm,
  .right {
    margin: 0 3.333%;
    display: flex;
    flex-wrap: wrap;
  }

  :deep(.el-form-item--default) {
    margin-bottom: 13px;
  }
}

.my-header {
  display: flex;
  flex-direction: row;
  font-size: 25px;
  color: #4d62a5;

  span:first-child {
    font-weight: 700;
    margin-right: 15px;
  }

  span:last-child {
    font-size: 22px;
  }
}

:deep(.el-dialog__body) {
  padding-top: 5px;
}

:deep(.el-divider--horizontal) {
  margin: 15px 0;
}

:deep(.el-form-item__label, .el-input__inner) {
  font-size: 12px;
}

.box {
  width: 100%;
  display: flex;
  flex-direction: column;

  .card-css {
    flex: 1;
    width: 100%;
    height: 800px;
    position: relative;

    .pagination {
      width: 100%;
      height: 3.125rem;
      margin-top: 1.25rem;

      .el-pagination {
        float: right;
        margin-right: 1.25rem;
      }
    }
  }

  .zhpj {
    position: absolute;
    border-bottom: 1px solid #d9deec;
    margin-right: 120px;
    margin-left: -20px;
    padding-left: 20px;
    padding-bottom: 20px;
    width: 100%;

    .zhpj-span {
      font-family: SourceHanSansSC-medium;
      font-weight: 700;
      color: #4d62a5;
      font-size: 20px;
    }
  }

  .table-css {
    display: flex;
    margin-top: 66px;
    justify-content: space-between;

    .switch-css {
      color: #8faadc;
      margin-left: 10px;
    }

    :deep(.el-switch.is-checked .el-switch__core) {
      background-color: #8faadc;
      border-color: #8faadc;
    }

    .biaotou-css {
      display: flex;

      .select01 {
        width: 100px;
      }

      .select02 {
        width: 100px;
        margin-right: 20px;
        margin-left: 20px;
      }

      .btn-01 {
        margin-left: 20px;
        margin-right: 20px;
      }

      .el-button {
        background-color: #8faadc;
        border-color: #8faadc;
      }

      .btn-css {
        flex-grow: 1;
      }
    }
  }

  .table {
    margin-top: 20px;
    margin-bottom: 20px;
  }
}
</style>
